package com.lc.luzhengtang.activity;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lc.luzhengtang.R;
import com.lc.luzhengtang.conn.Conn;
import com.lc.luzhengtang.view.HackyViewPager;
import com.zcx.helper.photo.PhotoView;
import com.zcx.helper.photo.PhotoViewAttacher;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;
import java.util.ArrayList;
import java.util.UUID;


/**
 * Created on 2016/7/19.
 * Author:crs
 * Description:XXX
 */
public class PhotoShowActivity extends Activity {

    private static final int REQUEST_DOWN = 1;
    private int position;
    private ArrayList<String> mDatas;
    private HackyViewPager hViewPager;

    private TextView text_images_count;

    Button bn_save;

    public static String getUUID() {
        UUID uuid = UUID.randomUUID();
        String str = uuid.toString();
// 去掉"-"符号
        String temp = str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23) + str.substring(24);
        return temp;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_show);
        text_images_count = (TextView) findViewById(R.id.text_images_count);
        bn_save = (Button) findViewById(R.id.bn_save);
        bn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("onClick", "onClick");
                if (ActivityCompat.checkSelfPermission(PhotoShowActivity.this, Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
                    // Camera permission has not been granted.

                    requestDownPermission();

                } else {

                    downPic();
//                    // Camera permissions is already available, show the camera preview.
//                    Log.i(TAG,
//                            "CAMERA permission has already been granted. Displaying camera preview.");
//                    showCameraPreview();
                }
            }
        });

       /* findViewById(R.id.bn_save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {



            }
        });*/
        getFrontPageData();
        initViews();
        hViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                text_images_count.setText(position + 1 + "/" + mDatas.size() + "");
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void requestDownPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
                REQUEST_DOWN);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_DOWN) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                downPic();
                // Camera permission has been granted, preview can be displayed
//                Log.i(TAG, "CAMERA permission has now been granted. Showing preview.");
//                Snackbar.make(mLayout, R.string.permision_available_camera,
//                        Snackbar.LENGTH_SHORT).show();
            } else {
                requestDownPermission();

            }
        } else
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void downPic() {
        int currentItem = hViewPager.getCurrentItem();
        String url = Conn.HOST3 + mDatas.get(currentItem);

        String fileDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/photos";
        Log.d("downPic", "fileDir = " + fileDir);
//        String fileDir = Environment.getDataDirectory().getAbsolutePath() + "/photos";
//               final String fileDir = SAVE_PIC_PATH+ "/savePic";//保存的确切位置
        final File file = new File(fileDir);

        if (!file.exists()) {
            file.mkdir();
        }

        OkHttpUtils
                .get()
                .url(url)
                .build()
                .execute(new FileCallBack(file.getAbsolutePath(), getUUID() + ".jpg") {
                    @Override
                    public void onError(okhttp3.Call call, Exception e, int id) {
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        Toast.makeText(PhotoShowActivity.this, "下载成功，图片保存在" + response.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                      /*  Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri uri = Uri.fromFile(file);
                        intent.setData(uri);
                        context.sendBroadcast(intent);//*/
                    }
                });
    }

    private void initViews() {
        hViewPager = (HackyViewPager) findViewById(R.id.hViewPager);
        hViewPager.setAdapter(new ImageAdapter());
        //为ViewPager当前page的数字
        hViewPager.setCurrentItem(position);

    }

    public void getFrontPageData() {
        //点击图片的位置
        position = getIntent().getIntExtra("position", 0);
        //获取传递过来的图片地址
        mDatas = getIntent().getStringArrayListExtra("mImages");

    }


    public class ImageAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return null == mDatas ? 0 : mDatas.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            //创建显示图片的控件
            PhotoView photoView = new PhotoView(container.getContext());
            //设置背景颜色
            photoView.setBackgroundColor(Color.BLACK);
            //把photoView添加到viewpager中，并设置布局参数
            container.addView(photoView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            //加载当前PhtotoView要显示的数据
            String url = Conn.HOST3 + mDatas.get(position);

            if (!TextUtils.isEmpty(url)) {
                //使用使用Glide进行加载图片进行加载图片
                Glide.with(PhotoShowActivity.this).load(url).error(R.mipmap.zhanwei).placeholder(R.mipmap.zhanwei).into(photoView);
            }

            //图片单击事件的处理
            photoView.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {
                @Override
                public void onViewTap(View view, float x, float y) {
                    finish();
                }
            });
            return photoView;
        }
    }
}
